/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.platformservice.persistence.c14n;

import org.proteusframework.platformservice.persistence.messagebean.DataType;

import java.io.*;
import java.util.Arrays;

/**
 * @author Tacoma Four
 */
final class SerializationC14NHandler extends AbstractC14NHandler
{
    @Override
    public Object fromC14N(byte[] bytes)
    {
        Object value = null;

        try
        {
            ObjectInputStream serIs = new ObjectInputStream(new ByteArrayInputStream(bytes));
            value = serIs.readObject();
        } catch (IOException e)
        {
            e.printStackTrace();
        } catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }

        return value;
    }

    @Override
    public byte[] toC14N(Object object)
    {
        byte[] c14nBytes = new byte[0];

        try
        {
            ByteArrayOutputStream serializedBytesStream = new ByteArrayOutputStream();
            ObjectOutputStream serOs = new ObjectOutputStream(serializedBytesStream);
            serOs.writeObject(object);
            serOs.flush();
            serOs.close();
            byte[] serializedBytes = serializedBytesStream.toByteArray();

            String serHeader = PACKED_BLOB_PREFIX + DataType.SerializableType.ordinal() + PACKED_BLOB_SUFFIX;
            byte[] serHeaderBytes = serHeader.getBytes();

            ByteArrayOutputStream packedBaos = new ByteArrayOutputStream();
            packedBaos.write(serHeaderBytes, 0, serHeaderBytes.length);
            packedBaos.write(serializedBytes, 0, serializedBytes.length);

            c14nBytes = packedBaos.toByteArray();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        return c14nBytes;
    }
}
